package com.yuwei.goods_detail.entity

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.text.style.ReplacementSpan

class RoundedTagSpan(
    private val backgroundColor: Int,//背景颜色
    private val textColor: Int,//文字颜色
    private val cornerRadius: Float = 8f, // 圆角半径
    private val horizontalPadding: Int = 8, // 左右内边距（像素）
    private val verticalPadding: Int = 4 // 上下内边距（像素）
) : ReplacementSpan() {

    private var tagWidth = 0
    private var tagHeight = 0
    //计算文字的长宽
    override fun getSize(
        paint: Paint,
        text: CharSequence,
        start: Int,
        end: Int,
        fm: Paint.FontMetricsInt?
    ): Int {
        // 计算文本宽度 + 左右内边距
        tagWidth = paint.measureText(text, start, end).toInt() + horizontalPadding * 2

        // 计算标签高度（基于字体 metrics + 上下内边距）
        fm?.let {
            tagHeight = (it.descent - it.ascent + verticalPadding * 2).toInt()
        }

        return tagWidth
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        // 保存原有画笔状态
        val originalColor = paint.color
        val originalStyle = paint.style

        // 绘制带圆角的背景
        paint.color = backgroundColor
        paint.style = Paint.Style.FILL

        // 计算背景矩形
        val rect = RectF(
            x,
            top.toFloat(),
            x + tagWidth,
            top.toFloat() + tagHeight
        )

        // 绘制圆角矩形背景
        canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)

        // 绘制文本（确保水平和垂直居中）
        paint.color = textColor

        // 计算文本基线位置（垂直居中）
        val textHeight = paint.descent() - paint.ascent()
        val textOffset = (textHeight / 2) - paint.descent()
        val textY = top + tagHeight / 2 + textOffset

        // 绘制文本（水平居中已通过 padding 实现）
        canvas.drawText(text, start, end, x + horizontalPadding, textY, paint)

        // 恢复画笔状态
        paint.color = originalColor
        paint.style = originalStyle
    }
}